package com.fq.wechat.controller;

import com.fq.wechat.action.WXAction;
import com.fq.wechat.constant.CommonConstant;
import com.fq.wechat.constant.MsgKey;
import com.fq.wechat.service.CC3200Service;
import com.fq.wechat.service.FollowerService;
import com.fq.wechat.util.MsgInvokeUtil;
import com.fq.wechat.util.MsgTypeInvokeUtil;
import com.fq.wechat.util.RequestUtil;
import com.fq.wechat.util.ResponseContainer;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author jifang.
 * @since 2016/4/3 11:40.
 */
@Controller
@RequestMapping("/wechat")
public class WeChatController {

    private Logger LOGGER = LoggerFactory.getLogger(WeChatController.class);

    @Autowired
    private FollowerService fService;

    @Autowired
    private CC3200Service cService;

    @Autowired
    private WXAction action;

    @RequestMapping(value = "/index.do", method = {RequestMethod.POST, RequestMethod.GET})
    public void index(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        Map<String, String> data = RequestUtil.parseDataToMap(request);
        if (checkSequence(data, response)) {
            String msgType = data.get(CommonConstant.MSG_TYPE);
            MsgTypeInvokeUtil.invoke(msgType, this, data, response);
        }
    }


    /**
     * 处理文本消息
     *
     * @param data
     * @param response
     * @throws IOException
     */
    private void onText(Map<String, String> data, HttpServletResponse response) throws IOException {
        String wxMsg = data.get(CommonConstant.CONTENT);
        String key = RequestUtil.parseMsgToKey(wxMsg);
        MsgInvokeUtil.invoke(key, action, data, response);
    }

    /**
     * 处理语音消息
     *
     * @param data
     * @param response
     * @throws IOException
     */
    private void onVoice(Map<String, String> data, HttpServletResponse response) throws IOException {
        String wxMsg = data.get(CommonConstant.RECOGNITION);
        String key = RequestUtil.parseMsgToKey(wxMsg);
        MsgInvokeUtil.invoke(key, action, data, response);
    }

    /**
     * 处理事件消息
     *
     * @param data
     * @param response
     * @throws IOException
     */
    private void onEvent(Map<String, String> data, HttpServletResponse response) throws IOException {
        String event = data.get(CommonConstant.U_EVENT);
        // 微信菜单消息
        if (event.equals(CommonConstant.CLICK)) {
            String wxMsg = data.get(CommonConstant.EVENT_KEY);
            String key = RequestUtil.parseMsgToKey(wxMsg);
            MsgInvokeUtil.invoke(key, action, data, response);
        }
        // 关注
        else if (event.equals(CommonConstant.SUBSCRIBE)) {
            String follower = data.get(CommonConstant.FROM_USER_NAME);
            fService.addFollower(follower);
            String content = "欢迎关注智能云家居公众号, 请点击右下方查看用户手册!";
            action.sendResponse(data, content, ResponseContainer.MUSIC.get(MsgKey.E_MANUAL), response);
        }
        // 取消关注
        else if (event.equals(CommonConstant.UN_SUBSCRIBE)) {
            String follower = data.get(CommonConstant.FROM_USER_NAME);
            String sequence = fService.getFollowerSequence(follower);
            if (!Strings.isNullOrEmpty(sequence)) {
                cService.removeSensor(sequence);
            }
            fService.removeFollower(follower);
        }
    }

    /**
     * 处理其他消息
     *
     * @param data
     * @param response
     * @throws IOException
     */
    private void onDefault(Map<String, String> data, HttpServletResponse response) throws IOException {
        action.do_default(data, response);
    }

    private boolean checkSequence(Map<String, String> data, HttpServletResponse response) {

        // 如果是关注/取消关注公众号, 则直接放过
        String eventKey = data.get(CommonConstant.U_EVENT);
        if (!Strings.isNullOrEmpty(eventKey)
                &&
                (eventKey.equals(CommonConstant.SUBSCRIBE) || eventKey.equals(CommonConstant.UN_SUBSCRIBE))) {
            return true;
        }

        String content = data.get(CommonConstant.CONTENT);
        if (!Strings.isNullOrEmpty(content) && content.contains("绑定")) {
            return true;
        }

        String follower = data.get(CommonConstant.FROM_USER_NAME);
        String sequence = fService.getFollowerSequence(follower);
        if (Strings.isNullOrEmpty(sequence)) {
            action.sendResponse(data, "尚未绑定任何设备, 请输入\"绑定(设备序列号)\"进行绑定", null, response);
            return false;
        } else {
            data.put(CommonConstant.SEQUENCE, sequence);
            return true;
        }
    }
}
